package com.tony.service.impl;

import java.math.BigDecimal;

import org.apache.log4j.Logger;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.tony.dao.AccountDAO;
import com.tony.dataobject.AccountDO;
import com.tony.result.AccountResult;
import com.tony.service.AccountManager;
import com.tony.util.LoggerUtil;

public class AccountManagerImpl implements AccountManager {

    public static final Logger  logger = Logger.getLogger("service.log");

    private AccountDAO          accountDAO;

    private TransactionTemplate transactionTemplate;

    @Override
    public AccountResult deposit(final String email, final BigDecimal depositAmount) {

        LoggerUtil.info(logger, "开始充值[" + email + "]，金额[" + depositAmount.toEngineeringString()
                                + "]元");

        AccountResult result = new AccountResult();

        try {
            transactionTemplate.execute(new TransactionCallback<Object>() {

                @Override
                public Object doInTransaction(TransactionStatus arg0) {

                    AccountDO accountDO = accountDAO.lockByEmail(email);

                    accountDO.setEmail(email);

                    BigDecimal newBalance = accountDO.getBalance().add(depositAmount);

                    accountDO.setBalance(newBalance);

                    accountDAO.update(accountDO);

                    return null;
                }

            });

        } catch (Exception e) {

            LoggerUtil.error(logger, email + "充值失败[" + depositAmount + "]", e);

            result.setSuccess(false);
        }

        LoggerUtil.info(logger, "充值成功[" + email + "]，金额[" + depositAmount.toEngineeringString()
                                + "]元");

        return result;
    }

    /**
     * Setter method for property <tt>accountDAO</tt>.
     * 
     * @param accountDAO value to be assigned to property accountDAO
     */
    public void setAccountDAO(AccountDAO accountDAO) {
        this.accountDAO = accountDAO;
    }

    /**
     * Setter method for property <tt>transactionTemplate</tt>.
     * 
     * @param transactionTemplate value to be assigned to property transactionTemplate
     */
    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }
}
